#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "options.h"

#include "global.h"
#include "utils/text.h"
#include "fetch/checker.h"
#include "fetch/fetchOpen.h"
#include "fetch/fetchPipe.h"
#include "interf/output.h"
#include "utils/mypthread.h"

#include "utils/debug.h"

static void cron ();

///////////////////////////////////////////////////////////
#ifdef PROF
static bool stop = false;
static void handler (int i) {
  global::seen->save();

  stop = true;
}
#endif // PROF


///////////////////////////////////////////////////////////
// If this thread terminates, the whole program exits
int main (int argc, char *argv[]) {
  // create all the structures
  global glob(argc, argv);
#ifdef PROF
  signal (SIGINT, handler);//keyboard interrupt
#endif // PROF
  time_t old = global::now;
  for (;;) {
    // update time
    global::now = time(NULL);
    stateMain(1);
    for (int i=0; i<global::maxFds; i++)
      global::ansPoll[i] = 0;
    for (uint i=0; i<global::posPoll; i++)
      global::ansPoll[global::pollfds[i].fd] = global::pollfds[i].revents;
    global::posPoll = 0;
    //if(isStart||global::waitDuration==0||global::now-old>global::waitDuration)
    //{
        fetchOpen();

   // }
    //isStart=false;

    checkAll();
    poll(global::pollfds, global::posPoll, 10);
    if (old != global::now) {
       // this block is called every second
	 cron();
	 old=global::now;
     }
  }
}

// a lot of stats and profiling things
static void cron () {
#ifdef PROF
	if(stop)
		exit(0);
#endif
	checkTimeout(); //check if there are timeout connections
	/*if (global::URLsDisk->getLength() == 0
      && global::URLsPriority->getLength() == 0 &&global::freeConns->getLength()==global::nb_conn
      )
    exit(0);

*/
	//stat
	int ramSize=global::URLsPriority->getLength();
	int diskSize=global::URLsDisk->getLength();
	int freeConnsNum=global::freeConns->getLength();
#ifdef STATS
	printf("timeout connections:%d\tfailed to connect:%d\tram urls:%d\tdisk urls:%d\t free conns:%d\t dup urls:%d\n",timeoutConn,failedConn,ramSize,diskSize,freeConnsNum,dupUrl);
#endif

}
